package com.stone.project.config;

import com.stone.project.domain.SysMenuPermission;
import com.stone.project.mapper.SysMenuPermissionMapper;
import com.stone.project.mapper.SysRoleMapper;
import com.stone.project.service.SysMenuPermissionService;
import com.stone.project.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.*;

/**
 * @author stone
 * 创建日期  2022/11/9
 *
 *
 * 提供需要健全的资源接口
 */
@Component
public class ConsumorFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private SysMenuPermissionService sysMenuPermissionService;

    @Autowired
    private SysRoleService sysRoleService;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 查找访问该资源，需要的权限
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation filterInvocation = ((FilterInvocation) object);
        String requestUrl = filterInvocation.getRequestUrl();


        //查询所有的资源
        Set<String> permissions = ((SysMenuPermissionMapper)sysMenuPermissionService.getBaseMapper()).findPermissions();
        Set<String> tmpPermissionLs = new HashSet<>();

        permissions.parallelStream()
                .forEach(e->{
                    if (antPathMatcher.match(e,requestUrl)){
                        //查询资源需要的所有的角色
                        Set<String> roleName = ((SysRoleMapper) sysRoleService.getBaseMapper()).findByPermissions(e);
                        tmpPermissionLs.addAll(roleName);
                    }
                });

        return SecurityConfig.createList(tmpPermissionLs.toArray(new String[tmpPermissionLs.size()]));
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}